<template>
  <a-modal
    title="选择角色"
    :visible="visible"
    v-bind="commonDlgProps"
    :width="600"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-form-item label="选择角色">
          <a-select mode="multiple" v-decorator="['roleIds', { rules: [{ required: true, message: '角色不能为空' }] }]">
            <a-select-option v-for="r in selectRoles" :key="r.id" :value="r.id" :disabled="r.disabled">{{
              r.name
            }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { dialogMixin } from '@/utils/mixin';
import { addRole } from '@/api/authenticationCenter/config/userGroup';
import { getRoleList } from '@/api/authenticationCenter/config/role';

export default {
  name: 'GroupSelectRole',
  mixins: [dialogMixin],
  data() {
    return {
      visible: false,
      form: this.$form.createForm(this),
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 4
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 20
        }
      },
      confirmLoading: false,
      selectRoles: []
    };
  },
  props: {
    groupId: {
      type: [Number, String]
    },
    roles: {
      type: Array,
      default() {
        return [];
      }
    },
    appId: {
      type: [Number, String],
      required: true
    }
  },
  created() {
    // this.form = this.$form.createForm(this);
  },
  watch: {
    visible(nv) {
      if (nv) {
        this.getSelectRoles();
      }
    }
  },
  methods: {
    open() {
      this.visible = true;
    },
    getSelectRoles() {
      getRoleList({
        appId: this.appId,
        pageNo: 1,
        status: 1,
        pageSize: 999
      }).then(res => {
        res.data.data.forEach(item => {
          this.roles.forEach(role => {
            if (item.id === role.roleId) {
              item.disabled = true;
            }
          });
        });
        this.selectRoles = res.data.data.filter(d => d.status === 1);
      });
    },
    handleOk() {
      // 触发表单验证
      this.form.validateFields((err, values) => {
        // 验证表单没错误
        if (!err) {
          console.log('form values', values);
          this.confirmLoading = true;
          addRole({
            groupId: this.groupId,
            ...values
          })
            .then(() => {
              this.confirmLoading = false;
              this.handleCancel();
              this.$emit('ok');
            })
            .catch(() => {
              this.confirmLoading = false;
            });
        }
      });
    },
    handleCancel() {
      this.confirmLoading = false;
      this.form.resetFields();
      this.visible = false;
    }
  }
};
</script>
